﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using CarolLib.Extension;
using DCS.Business.Model;
using CarolLib;
using CarolLib.FTP;
using System.Net;

namespace DemoWinApp
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{




			#region Old

			//FileStatus a = FileStatus.StartDownload;
			//FileStatus b = FileStatus.FinishDownload;
			//FileStatus c = a | b;

			//FileStatus d = FileStatus.StartParse;

			//MessageBox.Show(((c^b) & b).ToString());

			//Regex rg = new Regex("[0-9A-Z]{3,7}/[0-9]{2}[A-Z]{3}[0-9]{2}.");

			//string text = "MU0517/07SEP10.B5475.C8Y162.02/07";

			//var result = rg.IsMatch(text);

			//MessageBox.Show(result.ToString());
			//MessageBox.Show(text.Substring(0, 2));
			//MessageBox.Show(text.Substring(2, text.IndexOf('/') - 2));

			#endregion
		}


		private void button1_Click(object sender, EventArgs e)
		{
			#region Old

			//System.IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);

			//DateTime dt = DateTime.ParseExact("14Jan05", "ddMMMyy", culture);
			//MessageBox.Show(dt.ToString());


			//Regex rgPDate = new Regex(@"[0-9A-Z]{2,20}\.[0-9]{2}/[0-9]{2}");
			//string text = "MU0517/07SEP10.B5475.C8Y162.02/07";

			//MessageBox.Show(rgPDate.Match(text).Value);

			//MessageBox.Show("C8Y162.02/07");

			//char[] dot = { '.' };
			//char[] slash = { '/' };
			//Regex rgPDate = new Regex(@"[0-9A-Z]{2,20}\.[0-9]{2}/[0-9]{2}");
			//string text = "PAX/0/88";
			//string[] block = text.Split(dot,StringSplitOptions.RemoveEmptyEntries);

			//string[] t = text.Replace("PAX", string.Empty).Split(slash);
			//MessageBox.Show(text);

			#endregion

			TestParseLDM();

			PerformanceHelper.Time("try", 100, () => TestParseLDM(), Print);
		}

		private void TestParseLDM()
		{
			DCSFile file = new DCSFile() { LocalFileName = "MU0517_07SEP10_WUH_LSP.txt", LocalPath = "D:\\离岗下载中心\\mullsp\\" };
			var result = Parse(file);
		}

		static System.IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
		static Regex rgFirstLine = new Regex("[0-9A-Z]{3,7}/[0-9]{2}[A-Z]{3}[0-9]{2}.");
		static Regex rgPDate = new Regex("[0-9]{2}[A-Z]{3}[0-9]{2}");
		static Regex rgRegNo = new Regex(@"\.[0-9A-Z]{3,7}\.");
		static Regex rgLayout = new Regex(@"[0-9A-Z]{2,20}\.[0-9]{2}/[0-9]{2}");
		static Regex rgLspHeader = new Regex(@"[0-9]{2}[A-Z]{3}[0-9]{2} [0-9]{4}");
		static char[] dot = { '.' };
		static char[] slash = { '/' };

		private List<LDMMessage> Parse(DCSFile item)
		{
			List<LDMMessage> list = new List<LDMMessage>();
			LDMMessage model = null;
			LDMMessage model2 = null;

			using (FileStream fs = new FileStream(item.LocalPath + item.LocalFileName, FileMode.Open))
			{
				using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
				{
					string text = string.Empty;

					while (!reader.EndOfStream)
					{
						text = reader.ReadLine();

						#region Parse

						if (text == "LDM")
						{
							model = new LDMMessage();

							#region MU0517/07SEP10.B5475.C8Y162.02/07

							text = reader.ReadLine();

							if (rgFirstLine.IsMatch(text))
							{
								model.Carrier = text.Substring(0, 2);
								model.FlightNo = text.Substring(2, text.IndexOf('/') - 2);
								string pdate = rgPDate.Match(text).Value;
								model.PDate = DateTime.ParseExact(pdate, "ddMMMyy", culture);
								model.RegNo = rgRegNo.Match(text).Value.Replace(".", string.Empty);
								string[] last = rgLayout.Match(text).Value.Split(dot);
								model.Crew = last[1];
								model.PaxLayout = last[0];
							}

							#endregion

							text = reader.ReadLine();
							if (text.StartsWith("-"))
							{
								#region -PVG.104/0/0.0.T673.2/673

								model.ArrAirport = text.Substring(1, 3);
								string[] block = text.Substring(5).Split(dot);

								string[] ps = block[0].Split(slash);
								model.Adult = ps[0].TryToInt();
								model.Child = ps[1].TryToInt();
								model.Baby = ps[2].TryToInt();

								model.BagWeight = block[1].TryToInt();
								model.LoadTotal = block[2].Substring(1).TryToInt();
								model.LoadInCompartment = text.Substring(text.IndexOf(block[2]) + block[2].Length + 1);

								#endregion

								#region .PAX/2/102.PAD/0/0

								text = reader.ReadLine();
								ps = text.Split(dot, StringSplitOptions.RemoveEmptyEntries);
								string[] paxs = ps[0].Replace("PAX", string.Empty).Split(slash);
								string[] pads = ps[1].Replace("PAD", string.Empty).Split(slash);

								model.PaxF = paxs[0].TryToInt();
								model.PaxC = paxs[1].TryToInt();
								model.PaxY = paxs[2].TryToInt();
								model.PadF = pads[0].TryToInt();
								model.PadC = pads[1].TryToInt();
								model.PadY = pads[2].TryToInt();

								#endregion

								list.Add(model);

								text = reader.ReadLine();
								if (text.StartsWith("-"))
								{
									model2 = model.Clone() as LDMMessage;

									#region -FUK.2/0/0.0.T28.3/28

									model2.ArrAirport = text.Substring(1, 3);
									block = text.Substring(5).Split(dot);

									ps = block[0].Split(slash);
									model2.Adult = ps[0].TryToInt();
									model2.Child = ps[1].TryToInt();
									model2.Baby = ps[2].TryToInt();

									model2.BagWeight = block[1].TryToInt();
									model2.LoadTotal = block[2].Substring(1).TryToInt();
									model2.LoadInCompartment = text.Substring(text.IndexOf(block[2]) + block[2].Length + 1);

									#endregion

									#region .PAX/0/2.PAD/0/0

									text = reader.ReadLine();
									ps = text.Split(dot, StringSplitOptions.RemoveEmptyEntries);
									paxs = ps[0].Replace("PAX", string.Empty).Split(slash);
									pads = ps[1].Replace("PAD", string.Empty).Split(slash);

									model2.PaxF = paxs[0].TryToInt();
									model2.PaxC = paxs[1].TryToInt();
									model2.PaxY = paxs[2].TryToInt();
									model2.PadF = pads[0].TryToInt();
									model2.PadC = pads[1].TryToInt();
									model2.PadY = pads[2].TryToInt();

									#endregion

									list.Add(model2);
									text = reader.ReadLine();
								}

								#region SI

								if (text.StartsWith("SI"))
								{


									text += reader.ReadToEnd();
									list.ForEach(d => d.AdditionalInfo = text);
								}

								#endregion
							}
						}

						#endregion
					}
				}
			}

			return list;
		}

		public void Print(string msg)
		{
			MessageBox.Show(msg);
		}

		private void button2_Click(object sender, EventArgs e)
		{
			string txt = "MU2295_10JAN11_CTU_PRL_PART3.txt";
			string groupName = txt.Substring(0, txt.IndexOf("_PART"));
			MessageBox.Show(groupName);

			//string tx = "SqlServer2005";
			//MessageBox.Show((Enum.Parse(typeof(ServerVersion), tx)).ToString());

			//string date = "Jan  9 10:50";
			//DateTime dt;

			//if (date.ToCharArray()[4] == ' ')
			//{
			//    dt = DateTime.ParseExact(date, "MMM  d HH:mm", culture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
			//}
			//else
			//{
			//    dt = DateTime.ParseExact(date, "MMM d HH:mm", culture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

			//}
			//MessageBox.Show(dt.ToString());

			//string s = "MU2073_06SEP10_PEK_PRL_PART7.txt";
			//MessageBox.Show(s.Substring(0, s.IndexOf("_PART")));
		}

		private void button3_Click(object sender, EventArgs e)
		{
			List<Price> list = new List<Price>();
			using (StreamReader vStreamReader = new StreamReader("D:\\test.txt", Encoding.Default))
			{
				string vLine;
				while ((vLine = vStreamReader.ReadLine()) != null)
				{
					list.Add(new Price(vLine));
				}
			}

			list.ForEach(p => textBox1.Text += "\r\n" + p.ToString());
		}

		private void button4_Click(object sender, EventArgs e)
		{
			Stack<string> stk = new Stack<string>();

			using (StreamReader vStreamReader = new StreamReader("D:\\test.txt", Encoding.Default))
			{
				string vLine;
				while ((vLine = vStreamReader.ReadLine()) != null)
				{
					stk.Push(vLine);
				}
			}

			StringBuilder sb = new StringBuilder();
			while (stk.Count > 0)
			{
				sb.AppendLine(stk.Pop());
			}
			this.textBox1.Text = sb.ToString();
		}

		private void button5_Click(object sender, EventArgs e)
		{
			string text = "SYM KMG MU5894/06SEP10  B5265   F8Y126         3/5/0    06SEP10 1950";
			string pdate = rgLspHeader.Match(text).Value;
			DateTime dt = DateTime.ParseExact(pdate, "ddMMMyy HHmm", culture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
			MessageBox.Show(dt.ToString());
		}

		private void button6_Click(object sender, EventArgs e)
		{
			//test ftp delete.
			FTPclient ftp = new FTPclient("10.6.183.172", true, "mumsg", "1q2w3e4r");
			ftp.FtpDelete(this.textBox2.Text.Trim());
		}

		static object locker = new object();

		private void button7_Click(object sender, EventArgs e)
		{
			//List<string> test = new List<string>();
			//for (int i = 0; i < 100; i++)
			//{
			//    test.Add(i.ToString());
			//}

			//foreach (var item in test)
			//{
			//    System.Threading.Thread.Sleep(100);
			//    testAsyc(item);
			//}

			//button7.Text = "OK";

			string line = "['2011-02-09','5.87','5.85','-0.06','-1.02%','5.82','5.92','34561','2029.38','0.47%'],";

			MessageBox.Show(line.Substring(2, 10));

		}

		private void testAsyc(string id)
		{
			WebRequest webRequest = WebRequest.Create("http://www.baidu.com");
			webRequest.BeginGetResponse(result =>
			{
				using (WebResponse webResponse = webRequest.EndGetResponse(result))
				{
					Console.WriteLine(id);
				}
			}, null);
		}

		private void button8_Click(object sender, EventArgs e)
        {
        //    PRLSyncer syncer = new PRLSyncer();
        //    syncer.Init();
        //    syncer.DetectAndSync();
		}
	}


	public class Price
	{
		public int Code;
		public double Weight;
		public double Value;

		public Price(string line)
		{
			int split2 = line.Substring(7).IndexOf('|');
			this.Code = line.Substring(0, 6).TryToInt();
			this.Weight = Convert.ToDouble(line.Substring(7, split2));
			this.Value = Convert.ToDouble(line.Substring(split2 + 8));
		}

		public override string ToString()
		{
			return string.Format("{0}|{1}|{2}", this.Code.ToString("000000"), Math.Round(this.Weight / 1.0), this.Value);
		}
	}

	public enum ServerVersion
	{
		SqlServer2000,
		SqlServer2005,
		SqlServer2008,
	}
}
